package com.example.yichuangyun.mvvm.ui.activity.order;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivitySearchOrderBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.order.OrderListDataModel;
import com.example.yichuangyun.model.order.OrderListParamsModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.CompanyDetailsActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.view.OrderListViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.OrderListAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 订单搜索
 */
public class SearchOrderActivity extends BaseActivity<ActivitySearchOrderBinding, OrderListViewModel> {

    private MyDialog myDialog;
    private OrderListParamsModel orderListParamsModel;
    private int page = 1;
    private OrderListAdapter adapter;
    private OrderListDataModel.OrderRecordsModel orderRecordsModel;
    private int mPosition;
    private String mTelNumber;
    private String businessId;
    private String clientName;
    /**
     * 0电话拨打、1款项确认
     */
    private int flag;
    private String orderId;

    @Override
    protected OrderListViewModel bindModel() {
        return getViewModel(this, OrderListViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        orderListParamsModel = new OrderListParamsModel();
        initDialog();
        adapter = new OrderListAdapter(context);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(context, R.layout.layout_empty_list);
    }

    private void getOrderList(int page) {
        orderListParamsModel.setCurrent(page);
        orderListParamsModel.setKeyValue(binding.etSearchContent.getText().toString().trim());
        viewModel.getOrderList(orderListParamsModel);
    }

    @Override
    protected void initClick() {
        viewModel.data.observe(this, orderListDataModel -> {
            if (orderListDataModel != null) {
                if (null != orderListDataModel.getRecords()) {
                    if (orderListDataModel.getRecords().size() < Constant.pageSize) {
                        binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
                if (page == 1) {
                    if (null == orderListDataModel.getRecords() || orderListDataModel.getRecords().isEmpty()) {
                        adapter.setEmptyViewLayout(context, R.layout.layout_empty_list);
                    }
                    binding.smartRefreshLayout.resetNoMoreData();
                    adapter.submitList(orderListDataModel.getRecords());
                    binding.smartRefreshLayout.finishRefresh();
                } else {
                    adapter.addAll(orderListDataModel.getRecords());
                    binding.smartRefreshLayout.finishLoadMore();
                }
            }
            dismissLoadingDialog();
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getOrderList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getOrderList(page);
            }
        });

        binding.tvCancel.setOnClickListener(v -> finish());
        binding.etSearchContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (!TextUtils.isEmpty(binding.etSearchContent.getText().toString().trim())) {
                    CommonUtil.closeKeyboard(SearchOrderActivity.this);
                    page = 1;
                    binding.recyclerView.scrollToPosition(0);
                    binding.smartRefreshLayout.autoRefresh();
                } else {
                    ToastHelper.show(getString(R.string.please_input_keyword));
                }
                return true;
            }
            return false;
        });

        viewModel.confirmSuccessData.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(getString(R.string.confirm_success));
            orderRecordsModel.setMoneyConfirmStatus(1);
            adapter.notifyItemChanged(mPosition, 1);
        });

        viewModel.mErrorData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });

        adapter.addOnItemChildClickListener(R.id.ll_call, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                mTelNumber = orderRecordsModel.getPhone();
                businessId = orderRecordsModel.getBusinessId();
                clientName = orderRecordsModel.getUsername();
                myDialog.setIconVisibility(View.GONE);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, false);
            }
        });
        adapter.addOnItemChildClickListener(R.id.tv_phone, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                mTelNumber = orderRecordsModel.getPhone();
                businessId = orderRecordsModel.getBusinessId();
                clientName = orderRecordsModel.getUsername();
                myDialog.setIconVisibility(View.GONE);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, false);
            }
        });
        adapter.addOnItemChildClickListener(R.id.ll_payment_confirm, (baseQuickAdapter, view, i) -> {
            flag = 1;
            mPosition = i;
            orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                double price = orderRecordsModel.getPrice();
                double payedPrice = orderRecordsModel.getPayedPrice();
                orderId = orderRecordsModel.getId();
                if (payedPrice < price) {
                    ToastHelper.show(getString(R.string.unable_payment_confirm));
                } else {
                    myDialog.setText(context.getString(R.string.order_finish_pay_confirm), context.getString(R.string.order_payment_confirm_tips), context.getString(R.string.cancel), context.getString(R.string.confirm));
                    myDialog.setIconVisibility(View.VISIBLE);
                    myDialog.showDialog();
                }
            }
        });

        adapter.addOnItemChildClickListener(R.id.ll_add_follow, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.orderIdKey, orderRecordsModel.getId());
                bundle.putString(Constant.orderNoKey, orderRecordsModel.getOrderNo());
                JumpIntent.jump(SearchOrderActivity.this, OrderAddFollowActivity.class, bundle);
            }
        });

        adapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            orderRecordsModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.fromKey, 1);
            bundle.putString(Constant.idKey, orderRecordsModel.getId());
            JumpIntent.jump(this, OrderDetailsActivity.class, bundle);
        });

        adapter.addOnItemChildClickListener(R.id.tv_company_name, (baseQuickAdapter, view, i) -> {
            orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                if (orderRecordsModel.getEnterConfirmState() == 1) {
                    if (CommonUtil.isCanClick()) {
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.creditNoKey, orderRecordsModel.getCreditNo());
                        JumpIntent.jump(this, CompanyDetailsActivity.class, bundle);
                    }
                } else {
                    mPosition = i;
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.fromKey, 1);
                    bundle.putString(Constant.idKey, orderRecordsModel.getId());
                    JumpIntent.jump(this, OrderDetailsActivity.class, bundle);
                }
            }
        });
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                if (flag == 0) {
                    RequestUtils.callNum(context, mTelNumber);
                    Constant.pushBusinessId = businessId;
                }
            }

            @Override
            public void rightClick() {
                if (flag == 0) {
                    RequestUtils.callbackOutbound(context, mTelNumber, businessId, clientName);
                } else {
                    showLoadingDialog();
                    viewModel.moneyConfirm(orderId);
                    orderId = null;
                }
            }
        };
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshSearchOrderList)) {
                orderRecordsModel.setMoneyConfirmStatus(1);
                adapter.notifyItemChanged(mPosition, "1");
            }
        }
    }
}